//定位器专项数据列表分页
import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import {
    apiGetPage, apiGetPrice, apiGetExport
} from '@/request/dataBoard/durationOfRecharge'
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';

import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import { exportSheetTable } from '@/utils/exportTable.js';
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { transNumber } from "@/utils/numberTrans";
import Card from "@/views/dataBoard/components/card.jsx"

class TheNumberOfStatistics extends Component {
    constructor() {
        super()
        this.formRef_search = React.createRef()
        this.queryFormRef = React.createRef()
        this.voucherFormRef = React.createRef()
        this.state = {
            price: "",
            showArr: [],
            columns: [
                {
                    title: " id",
                    dataIndex: "businessId",
                    key: "businessId",
                    filterDropdown: true,
                    filterIcon: () => {
                        return (
                          <Tooltip zIndex={999} placement="top" title={() => { return <span>一次充值会话的id。</span> }}  >
                            <QuestionCircleOutlined />
                          </Tooltip>
                        );
                      },
                },
                {
                    title: "用户id",
                    dataIndex: "memberId",
                    key: "memberId",
                },

                {
                    title: "用户昵称",
                    dataIndex: "memberName",
                    key: "memberName",

                },
                {
                    title: "类型",
                    dataIndex: "businessType",
                    key: "businessType",
                    render: (txt, _) => {
                        let text = ''
                        switch (txt) {
                            case 'WALLET_RECHARGE':
                                text = '钱包充值'
                                break
                            case 'PET_COIN_RECHARGE':
                                text = '宠币充值'
                                break
                            default:
                                text = '/'
                                break
                        }
                        return text
                    }
                },
                {
                    title: "状态",
                    dataIndex: "tradeState",
                    key: "tradeState",
                    render: (txt, _) => {
                        let text = ''
                        switch (txt) {
                            case 'NOT_PAY':
                                text = '未支付'
                                break
                            case 'PAY_COMPLETE':
                                text = ' 支付完成'
                                break
                            case 'PAY_FAILURE':
                                text = ' 支付失败'
                                break
                            case 'TIMEOUT':
                                text = ' 支付超时'
                                break
                            default:
                                text = '/'
                                break
                        }
                        return text
                    }
                },
                {
                    title: "开始时间",
                    dataIndex: "initTime",
                    key: "initTime",
                    filterDropdown: true,
                    filterIcon: () => {
                        return (
                          <Tooltip zIndex={999} placement="top" title={() => { return <span>充值开始时间定义：一次充值会话，用户点击充值按钮（钱包充值） 、确认购买（宠币充值）的时间</span> }}  >
                            <QuestionCircleOutlined />
                          </Tooltip>
                        );
                      },
                },
                {
                    title: "结束时间",
                    dataIndex: "finishTime",
                    key: "finishTime",
                    filterDropdown: true,
                    filterIcon: () => {
                        return (
                            <Tooltip zIndex={999} placement="top" title={() => { return <span>充值结束时间定义：
                                1）一次充值会话中，用户充值成功的时间
                                2）一次充值会话中，用户点击关闭，导致取消充值流程的时间
                                3）一次充值会话中，app或者H5端超过30秒没有监控到用户的任何操作（包括滑动、点击），则记录用户当前已退出充值流程（这种情况是有可能用户把应用切换到后台锁定了，长时间未操作后再次打开页面则中间的时长不做记录）</span> }}  >
                                <QuestionCircleOutlined />
                            </Tooltip>
                        );
                    },
                },
                {
                    title: "停留时长（秒）",
                    dataIndex: "waitTimeSeconds",
                    key: "waitTimeSeconds",
                    filterDropdown: true,
                    filterIcon: () => {
                        return (
                            <Tooltip zIndex={999} placement="top" title={() => { return <span>每次充值会话的结束时间 减 开始时间的时长，保留整秒</span> }}  >
                                <QuestionCircleOutlined />
                            </Tooltip>
                        );
                    },
                },
            ],
            dataSource: [],
            dateSource2: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'times', label: '充值日期', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
                { field: "businessType", label: "类型", placeholder: "全部", type: "Select", options: [{ value: '', label: '全部' }, { value: 'WALLET_RECHARGE', label: '钱包充值' }, { value: 'PET_COIN_RECHARGE', label: '宠币充值' }] },
                { field: "tradeState", label: "状态", placeholder: "全部", type: "Select", options: [{ value: '', label: '全部' }, { value: 'NOT_PAY', label: '未支付' }, { value: 'PAY_COMPLETE ', label: '支付完成' }, { value: 'PAY_FAILURE ', label: '支付失败' }] },
            ],
            queryForm: {},
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let { pageNo, pageSize, queryForm, pathName } = searchParams
        if (searchParams && pageNo && pathName == 'theNumberOfStatistics') {
            this.setState({
                queryForm,
                pageData: {
                    pageNo: pageNo, pageSize: pageSize
                }
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                this.getData()
                this.getDateS()
            })
        } else {
            this.getData()
            this.getDateS()
        }
    }
    getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.times)) {
            values.startTime = getDateTime3(values.times[0]) + " 00:00:00"
            values.endTime = getDateTime3(values.times[1]) + " 23:59:59"
            delete (values.times)
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'theNumberOfStatistics',
                    ...params
                }
            })
            let res = await apiGetPage({
                pageNo, pageSize, ...this.state.queryForm,
            })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data.map((item,index)=>{
                        return {
                            index,
                            ...item,
                        }
                    }),
                    total: res.totalCount
                })
            }
        })
    }

    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
            this.getDateS(values)
        })
    }
    getDateS = async (values) => {
        let res = await apiGetPrice({
            ...values
        })
        if (res.code === 0) {
            let dateSource2 = [];
            dateSource2 = [
                {
                    top:
                    {
                        title: '平均充值时长(秒）',
                        value: res.data ? res.data.waitTimeSeconds : '',
                        explain: "平均充值时长= 筛选条件内所有充值次数的停留时长之和 / 筛选时间充值次数，保留2位有效数字",
                        yesterdayShow: true
                    },
                },
            ]
            this.setState({ dateSource2 })
        }
    }

    toExport = async () => {
        const { queryForm } = this.state
        await apiGetExport({ ...queryForm }).then(res => {
            if (res.code === 0 && res.data) {
                let th_arr = [
                    {
                        title: '充值时长专项统计',
                        prop: '',
                        children: [
                            {
                                title: "id",
                                prop: "businessId",
                            },
                            {
                                title: "用户id",
                                prop: "memberId",
                            },
                            {
                                title: "用户昵称",
                                prop: "memberName",
                            },
                            {
                                title: "类型",
                                prop: "businessType",
                            },
                            {
                                title: "状态",
                                prop: "tradeState",
                            },
                            {
                                title: "开始时间",
                                prop: "initTime",
                            },
                            {
                                title: "结束时间",
                                prop: "finishTime",
                            },
                            {
                                title: "停留时长（秒）",
                                prop: "waitTimeSeconds",
                            },
                        ]
                    },
                ]
                let tb_arr = []
                const getBusinessType = (txt) => {
                    let text = ''
                    switch (txt) {
                        case 'WALLET_RECHARGE':
                            text = '钱包充值'
                            break
                        case 'PET_COIN_RECHARGE':
                            text = '宠币充值'
                            break
                        default:
                            text = '/'
                            break
                    }
                    return text
                }
                const getTraderState = (txt) => {
                    console.log("------------------------", txt);
                    let text = ''
                    switch (txt) {
                        case 'NOT_PAY':
                            text = '未支付'
                            break
                        case 'PAY_COMPLETE':
                            text = ' 支付完成'
                            break
                        case 'PAY_FAILURE':
                            text = ' 支付失败'
                            break
                        case 'TIMEOUT':
                            text = ' 支付超时'
                            break
                        default:
                            text = '/'
                            break
                    }
                    return text
                }
                res.data.forEach((item, index) => {
                    tb_arr.push({
                        businessId: item.businessId || '/',
                        memberId: item.memberId || '/',
                        memberName: item.memberName || '/',
                        businessType: getBusinessType(item.businessType),
                        tradeState: getTraderState(item.tradeState),
                        initTime: item.initTime || '/',
                        finishTime: item.finishTime || '/',
                        waitTimeSeconds: item.waitTimeSeconds || '/',
                    })
                })
                exportSheetTable({ fileName: '充值时长专项统计', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
            }
        })

    }
    render() {
        let { columns, dataSource, pageData, total, form_show, searchOption, newColumns, price, showArr, dateSource2 } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onReset={() => this.onReset()}
                    onGetValues={(values) => this.onFormSearch(values)} >
                </TheQueryForm>
                <div className="card-box" >
                    {
                        dateSource2.map((v, i) => {
                            return <Card key={i} top={v.top} showArr={showArr} />
                        })
                    }
                </div>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
                </TheTableExtend>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                    rowKey={'businessId'}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
            </div>
        );
    }
}
export default TheNumberOfStatistics
